package com.example.core.cluster;

import com.example.core.latch.Latch;
import com.example.core.latch.LeaderLatchListener;
import com.example.core.latch.RedissonLeaderLatch;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysClusterServiceImpl implements SysClusterService, ApplicationContextAware, InitializingBean, LeaderLatchListener, DisposableBean {

    private Latch latch;

    private ApplicationContext applicationContext;

    @Resource
    private List<MasterServerService> masterServerServices = new ArrayList<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        this.latch = new RedissonLeaderLatch(getApplicationContext(), getClass().getName(), this::isLeader);
        this.latch.start();
    }

    @Override
    public void destroy() throws Exception {
        for (MasterServerService masterServerService : masterServerServices) {
            masterServerService.stop();
        }
        this.latch.stop();
    }

    @Override
    public void isLeader() {
        for (MasterServerService masterServerService : masterServerServices) {
            masterServerService.start();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
